package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.common.constants.ArticleSearchConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.HistorySearchDto;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.pojos.ApUserSearch;
import com.heima.search.service.ApArticleSearchService;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class ApArticleSearchServiceImpl implements ApArticleSearchService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * ES文章搜索
     * @param dto
     */
    @Override
    public ResponseResult search(UserSearchDto dto) {
        // 1. 检查参数
        if (dto == null || StringUtils.isBlank(dto.getSearchWords())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 保存用户搜索历史记录
        ApUser apUser = AppThreadLocalUtil.getUser();
        if (apUser != null && dto.getFromIndex() == 0){
            insert(dto.getSearchWords(),apUser.getId());
        }

        // 2. 创建用于搜索的请求对象
        SearchRequest searchRequest = new SearchRequest(ArticleSearchConstants.ARTICLE_SEARCH_INDEX);
        // 3. 构造DSL
        // 3.1 查询
        // 3.1.1 创建BoolQuery
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 3.1.2 创建QueryStringQuery
        QueryStringQueryBuilder queryStringQuery = QueryBuilders.queryStringQuery(dto.getSearchWords())
                .field("title").field("content")
                .defaultOperator(Operator.OR);
        boolQuery.must(queryStringQuery);
        // 3.1.3 创建RangeQuery
        RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime());
        boolQuery.filter(rangeQuery);
        // 3.1.4 在请求中添加BoolQuery
        searchRequest.source().query(boolQuery);
        // 3.2 分页
        searchRequest.source().from(dto.getFromIndex())
                .size(dto.getPageSize());
        // 3.3 排序
        searchRequest.source().sort("publishTime", SortOrder.DESC);
        // 3.4 高亮
        HighlightBuilder highLighter = new HighlightBuilder();
        highLighter.field("title");
        highLighter.preTags("<font style='color: red; font-size: inherit;'>");
        highLighter.postTags("</font>");
        searchRequest.source().highlighter(highLighter);
        try {
            // 4. 发送请求
            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            // 5. 解析响应
            List<Map> list = new ArrayList<>();
            SearchHit[] hits = searchResponse.getHits().getHits();
            for (SearchHit hit : hits) {
                String sourceJson = hit.getSourceAsString();
                Map map = JSON.parseObject(sourceJson, Map.class);
                // 高亮
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                if (!CollectionUtils.isEmpty(highlightFields)){
                    // 有高亮结果
                    HighlightField titleHighlightField = highlightFields.get("title");
                    if (titleHighlightField != null){
                        Text[] texts = titleHighlightField.getFragments();
                        map.put("h_title",texts[0].toString());
                    }
                }else {
                    // 没有高亮结果,使用原始title作为h_title
                    map.put("h_title",map.get("title"));
                }
                list.add(map);
            }
            // 返回响应结果
            return ResponseResult.okResult(list);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return  ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
    }


    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存用户搜索历史记录
     * @param keyword
     * @param userId
     */
    @Async
    @Override
    public void insert(String keyword, Integer userId) {
        // 1. 按照关键字和用户id查询搜索记录
        Query query = Query.query(Criteria.where("keyword").is(keyword).and("userId").is(userId));
        ApUserSearch apUserSearch = mongoTemplate.findOne(query, ApUserSearch.class);
        if (apUserSearch != null){
            // 2. 判断是否存在，如果已经存在，修改创建时间
            apUserSearch.setCreatedTime(new Date());
            mongoTemplate.save(apUserSearch); // 由于id存在，是修改
            return;
        }
        // 3. 如果不存在，查询当前用户的所有搜索记录,并按照创建时间降序排序
        Query query2 = Query.query(Criteria.where("userId").is(userId));
        query2.with(Sort.by(Sort.Direction.DESC,"createdTime"));
        List<ApUserSearch> apUserSearchList = mongoTemplate.find(query2, ApUserSearch.class);
        // 4. 判断搜索记录是否超过10条
        apUserSearch = new ApUserSearch();
        apUserSearch.setKeyword(keyword);
        apUserSearch.setUserId(userId);
        apUserSearch.setCreatedTime(new Date());
        if (apUserSearchList == null || apUserSearchList.size() < 10){
            // 如果没有超过，则保存新的记录
            mongoTemplate.save(apUserSearch);
        }else {
            // 5. 如果已经超过10条，替换最早的一条
            ApUserSearch oldPpUserSearch = apUserSearchList.get(apUserSearchList.size() - 1);
            mongoTemplate.findAndReplace(Query.query(Criteria.where("id").is(oldPpUserSearch.getId())),apUserSearch);
        }

    }

    /**
     * 查询当前登录用户的所有历史搜索记录
     * @return
     */
    @Override
    public ResponseResult findUserSearch() {
        // 1. 检查登录状态
        ApUser apUser = AppThreadLocalUtil.getUser();
        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 2. 按照userId查询所有历史记录
        Query query = Query.query(Criteria.where("userId").is(apUser.getId()));
        query.with(Sort.by(Sort.Direction.DESC,"createdTime"));
        List<ApUserSearch> apUserSearchList = mongoTemplate.find(query, ApUserSearch.class);
        return ResponseResult.okResult(apUserSearchList);
    }

    /**
     * 按照id删除用户历史搜索记录
     *
     * @param dto
     */
    @Override
    public ResponseResult delUserSearch(HistorySearchDto dto) {
        // 1. 检查登录状态
        ApUser apUser = AppThreadLocalUtil.getUser();
        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 2. 删除
        Query query = Query.query(Criteria.where("id").is(dto.getId()));
        mongoTemplate.remove(query,ApUserSearch.class);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
